package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.service.CouponRecordService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponMQListener {

    @Autowired
    private CouponRecordService couponRecordService;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 消费
     *
     * @param recordMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseCouponReocrd(CouponRecordMessage recordMessage, Message message, Channel channel) throws IOException {
        RLock lock = redissonClient.getLock("lock:coupon_record_release:" + recordMessage.getTaskId());
        lock.lock();
        log.info("监听到消息:releaseCouponReocrd消息内容:{}", recordMessage);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        boolean bl = couponRecordService.releaseCouponRecord(recordMessage);

        try {
            if (bl) {
                channel.basicAck(deliveryTag, false);
            } else {
                log.error("释放优惠券失败 flag=false,{}", recordMessage);
                channel.basicReject(deliveryTag, true);
            }
        } catch (IOException e) {
            log.error("释放优惠券记录异常:{}.msg:{}", e, recordMessage);
            channel.basicReject(deliveryTag, true);
        }
        finally {
            lock.unlock();
        }
    }
}
